<template>
  <el-card shadow="hover" class="management-card">
    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="简历名称">
        <el-input v-model="searchForm.resumeName" placeholder="请输入简历名称" clearable />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="header-actions">
      <el-button type="primary" @click="handleOpenDialog" class="create-resume-button">
        <el-icon class="el-icon--left">
          <Plus />
        </el-icon>
        创建新简历
      </el-button>
      <el-upload action="http://localhost:5000/api/uploadResume" :show-file-list="false" :on-success="handleSuccess"
        :before-upload="beforeUpload" class="upload-button">
        <el-button type="primary">
          <el-icon class="el-icon--left">
            <Plus />
          </el-icon>
          上传新简历
        </el-button>
      </el-upload>
    </div>

    <!-- 数据表格 -->
    <el-table :data="resumes" border stripe highlight-current-row style="width: 100%"
      header-row-class-name="custom-header">
      <el-table-column prop="title" label="简历名称" width="220" />
      <el-table-column prop="filePath" label="存储路径" show-overflow-tooltip />
      <el-table-column prop="createdAt" label="创建时间" width="247" />
      <el-table-column label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="row.status === '已启用' ? 'success' : 'warning'" effect="dark">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="{ row }">
          <div class="action-buttons">
            <el-button type="primary" size="small" plain @click="downloadResume(row)">
              <el-icon>
                <Download />
              </el-icon>
            </el-button>
            <el-button type="danger" size="small" plain @click="deleteResume(row.id)">
              <el-icon>
                <Delete />
              </el-icon>
            </el-button>
            <el-button :type="row.status === '已禁用' ? 'success' : 'warning'" size="small" plain
              @click="toggleStatus(row)">
              {{ row.status === '已禁用' ? '启用' : '禁用' }}
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination background layout="prev, pager, next, sizes, total" :total="total" :page-size="pageSize"
        :current-page="currentPage" @current-change="handlePageChange" @size-change="handleSizeChange" />
    </div>

    <!-- 创建简历对话框 -->
    <el-dialog v-model="dialogVisible" title="创建新简历" width="800px" @closed="handleDialogClosed">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <!-- 模板选择 -->
        <el-form-item label="选择模板" prop="templateId">
          <el-select v-model="form.templateId" placeholder="请选择简历模板" clearable style="width: 100%">
            <el-option v-for="template in templateOptions" :key="template.id" :label="template.templateName"
              :value="template.id" />
          </el-select>
        </el-form-item>
        <!-- 基本信息 -->
        <el-form-item label="简历名称" prop="resumeName">
          <el-input v-model="form.resumeName" placeholder="请输入简历名称" />
        </el-form-item>

        <el-divider>基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生年月" prop="birthDate">
              <el-date-picker v-model="form.birthDate" type="date" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="form.phone" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="政治面貌" prop="politicalStatus">
              <el-input v-model="form.politicalStatus" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="毕业院校" prop="school">
              <el-input v-model="form.school" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学历" prop="education">
              <el-select v-model="form.education" style="width: 100%">
                <el-option label="本科" value="本科" />
                <el-option label="硕士" value="硕士" />
                <el-option label="博士" value="博士" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 教育背景 -->
        <el-divider>教育背景</el-divider>
        <div v-for="(edu, index) in form.educations" :key="index" class="dynamic-item">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item :label="`经历 ${index + 1}`" :prop="`educations.${index}.startDate`"
                :rules="{ required: true, message: '请选择开始日期', trigger: 'change' }">
                <el-date-picker v-model="edu.startDate" type="date" value-format="YYYY-MM-DD" placeholder="开始日期"
                  style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :prop="`educations.${index}.endDate`"
                :rules="{ required: true, message: '请选择结束日期', trigger: 'change' }">
                <el-date-picker v-model="edu.endDate" type="date" value-format="YYYY-MM-DD" placeholder="结束日期"
                  style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-button type="danger" @click="removeEducation(index)" circle plain>
                <el-icon>
                  <Delete />
                </el-icon>
              </el-button>
            </el-col>
          </el-row>
          <el-form-item :prop="`educations.${index}.school`"
            :rules="{ required: true, message: '请输入院校名称', trigger: 'blur' }">
            <el-input v-model="edu.school" placeholder="院校名称" />
          </el-form-item>
          <el-form-item :prop="`educations.${index}.major`"
            :rules="{ required: true, message: '请输入专业名称', trigger: 'blur' }">
            <el-input v-model="edu.major" placeholder="专业名称" />
          </el-form-item>
          <el-form-item :prop="`educations.${index}.courses`"
            :rules="{ required: true, message: '请输入主修课程', trigger: 'blur' }">
            <el-input v-model="edu.courses" placeholder="主修课程（多个用逗号分隔）" />
          </el-form-item>
        </div>
        <el-button type="primary" @click="addEducation" plain>添加教育经历</el-button>

        <!-- 实习经历 -->
        <el-divider>实习经历</el-divider>
        <div v-for="(internship, index) in form.internships" :key="index" class="dynamic-item">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item :label="`经历 ${index + 1}`" :prop="`internships.${index}.startDate`"
                :rules="{ required: true, message: '请选择开始日期', trigger: 'change' }">
                <el-date-picker v-model="internship.startDate" type="date" value-format="YYYY-MM-DD" placeholder="开始日期"
                  style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :prop="`internships.${index}.endDate`"
                :rules="{ required: true, message: '请选择结束日期', trigger: 'change' }">
                <el-date-picker v-model="internship.endDate" type="date" value-format="YYYY-MM-DD" placeholder="结束日期"
                  style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-button type="danger" @click="removeInternship(index)" circle plain>
                <el-icon>
                  <Delete />
                </el-icon>
              </el-button>
            </el-col>
          </el-row>
          <el-form-item :prop="`internships.${index}.company`"
            :rules="{ required: true, message: '请输入公司名称', trigger: 'blur' }">
            <el-input v-model="internship.company" placeholder="公司名称" />
          </el-form-item>
          <el-form-item :prop="`internships.${index}.position`"
            :rules="{ required: true, message: '请输入职位名称', trigger: 'blur' }">
            <el-input v-model="internship.position" placeholder="职位名称" />
          </el-form-item>
          <el-form-item :prop="`internships.${index}.responsibilities`"
            :rules="{ required: true, message: '请输入工作职责', trigger: 'blur' }">
            <el-input v-model="internship.responsibilities" type="textarea" placeholder="工作职责（多个用逗号分隔）" />
          </el-form-item>
        </div>
        <el-button type="primary" @click="addInternship" plain>添加实习经历</el-button>

        <!-- 校园经历 -->
        <el-divider>校园经历</el-divider>
        <div v-for="(campus, index) in form.campuses" :key="index" class="dynamic-item">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item :label="`经历 ${index + 1}`" :prop="`campuses.${index}.startDate`"
                :rules="{ required: true, message: '请选择开始日期', trigger: 'change' }">
                <el-date-picker v-model="campus.startDate" type="date" value-format="YYYY-MM-DD" placeholder="开始日期"
                  style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :prop="`campuses.${index}.endDate`"
                :rules="{ required: true, message: '请选择结束日期', trigger: 'change' }">
                <el-date-picker v-model="campus.endDate" type="date" value-format="YYYY-MM-DD" placeholder="结束日期"
                  style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-button type="danger" @click="removeCampus(index)" circle plain>
                <el-icon>
                  <Delete />
                </el-icon>
              </el-button>
            </el-col>
          </el-row>
          <el-form-item :prop="`campuses.${index}.activityName`"
            :rules="{ required: true, message: '请输入活动名称', trigger: 'blur' }">
            <el-input v-model="campus.activityName" placeholder="活动名称" />
          </el-form-item>
          <el-form-item :prop="`campuses.${index}.role`" :rules="{ required: true, message: '请输入角色', trigger: 'blur' }">
            <el-input v-model="campus.role" placeholder="角色（如：组织者、参与者等）" />
          </el-form-item>
          <el-form-item :prop="`campuses.${index}.description`"
            :rules="{ required: true, message: '请输入描述', trigger: 'blur' }">
            <el-input v-model="campus.description" type="textarea" placeholder="描述（多个用逗号分隔）" />
          </el-form-item>
        </div>
        <el-button type="primary" @click="addCampus" plain>添加校园经历</el-button>

        <el-form-item label="自我评价" prop="selfEvaluation">
          <el-input v-model="form.selfEvaluation" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Download, Delete } from '@element-plus/icons-vue'
import { get } from '@/request/request.js'
import axios from 'axios'


// 数据相关
const resumes = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const currentUsername = localStorage.getItem('loginUsername')
const searchForm = ref({ resumeName: '' })
const dialogVisible = ref(false)
const currentResume = ref({
  id: null,
  title: '',
  studentId: '',
  templateName: '无',
  filePath: '',
  createdAt: null,
  status: '已启用'
})
const templateOptions = ref([])
const currentFilename = ref('')

// 表单数据
const form = reactive({
  templateId: null,
  studentId: localStorage.getItem('loginUsername'),
  resumeName: '',
  name: '',
  birthDate: '',
  phone: '',
  politicalStatus: '',
  email: '',
  school: '',
  education: '',
  educations: [{
    startDate: '',
    endDate: '',
    school: '',
    major: '',
    courses: ''
  }],
  internships: [{
    startDate: '',
    endDate: '',
    company: '',
    position: '',
    responsibilities: ''
  }],
  campuses: [{
    startDate: '',
    endDate: '',
    activityName: '',
    role: '',
    description: ''
  }], // 校园经历
  selfEvaluation: ''
})

// 表单验证规则
const rules = reactive({
  resumeName: [{ required: true, message: '请输入简历名称', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ]
})

// 获取模板数据
const fetchTemplates = async () => {
  try {
    const res = await get('/api/admin/resumes/all')
    templateOptions.value = res.data
  } catch (error) {
    ElMessage.error('获取模板失败')
  }
}
// 打开对话框时获取模板
const handleOpenDialog = () => {
  dialogVisible.value = true
  fetchTemplates()
}


// 动态添加教育经历
const addEducation = () => {
  form.educations.push({
    startDate: '',
    endDate: '',
    school: '',
    major: '',
    courses: ''
  })
}
// 动态添加实习经历
const addInternship = () => {
  form.internships.push({
    startDate: '',
    endDate: '',
    company: '',
    position: '',
    responsibilities: ''
  })
}
// 动态添加校园经历
const addCampus = () => {
  form.campuses.push({
    startDate: '',
    endDate: '',
    activityName: '',
    role: '',
    description: ''
  })
}

const removeEducation = (index) => {
  form.educations.splice(index, 1)
}
const removeInternship = (index) => {
  form.internships.splice(index, 1)
}
const removeCampus = (index) => {
  form.campuses.splice(index, 1)
}

// 提交表单
const submitForm = async () => {
  try {
    const response = await axios.post(
      'http://localhost:5000/api/createResume',
      form, // 直接传递整个表单对象
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    );
    console.log(form);

    ElMessage.success('提交成功')
    dialogVisible.value = false
    fetchResumes(currentPage.value) // 刷新简历列表
    // 处理响应...
  } catch (error) {
    console.error('提交失败:', error);
  }
};

const handleSearch = () => {
  currentPage.value = 1
  fetchResumes()
}
const handleReset = () => {
  searchForm.value = { resumeName: '' }
  handleSearch()
}

//获取数据
const fetchResumes = async (page = 1) => {
  try {
    const params = {
      ...searchForm.value,
      page: page,
      size: pageSize.value,
      studentId: currentUsername
    }

    const res = await get('/api/getResumes', params)
    resumes.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('获取简历列表失败')
  }
}

const handlePageChange = (page) => {
  currentPage.value = page
  fetchResumes(page)
}

const handleSizeChange = (size) => {
  pageSize.value = size
  fetchResumes()
}

//删除简历
const deleteResume = async (id) => {
  try {
    // await delete(`/api/resumes/${id}`)
    await get(`/api/deleteResume/${id}`)
    ElMessage.success('删除成功')
    fetchResumes(currentPage.value)
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

//下载简历
const downloadResume = async (row) => {
  const filePath = row.filePath
  const fileName = row.title
  if (!filePath) {
    ElMessage.error('文件路径不存在')
    return
  }

  const link = document.createElement('a')
  link.href = filePath
  link.download = row.title || fileName
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

//启用/禁用简历
const toggleStatus = async (row) => {
  const newStatus = row.status === '已启用' ? '已禁用' : '已启用'
  try {
    currentResume.value = { ...row, status: newStatus }
    await get('/api/updateResume', currentResume.value)
    row.status = newStatus
    fetchResumes(currentPage.value)
    ElMessage.success('更新状态成功')
  } catch (error) {
    ElMessage.error('更新状态失败')
  }
}

// 文件上传处理
const beforeUpload = (file) => {
  console.log(file)
  currentFilename.value = file.name
  const isAcceptType = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'].includes(file.type)
  if (!isAcceptType) {
    ElMessage.error('仅支持 PDF 和 Word 文档')
    return false
  }
  return true
}

// 文件上传成功处理
const handleSuccess = (res) => {
  const resumeData = { ...currentResume.value }
  resumeData.filePath = res.data
  resumeData.studentId = localStorage.getItem('loginUsername')
  resumeData.title = currentFilename.value
  get('/api/saveResume', resumeData)
  if (res.code === 200) {
    ElMessage.success('上传成功')
    fetchResumes()
  }
}

// 关闭对话框时重置表单
const handleDialogClosed = () => {
  form.templateId = null
  form.resumeName = ''
  form.name = ''
  form.birthDate = ''
  form.phone = ''
  form.politicalStatus = ''
  form.email = ''
  form.school = ''
  form.education = ''
  form.educations = [{
    startDate: '',
    endDate: '',
    school: '',
    major: '',
    courses: ''
  }]
  form.internships = [{
    startDate: '',
    endDate: '',
    company: '',
    position: '',
    responsibilities: ''
  }]
  form.campuses = [{
    startDate: '',
    endDate: '',
    activityName: '',
    role: '',
    description: ''
  }]
  form.selfEvaluation = ''
}

onMounted(() => {
  fetchResumes()
})

</script>

<style lang="scss" scoped>
.dynamic-item {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  padding: 15px;
  border-radius: 4px;

  &+.dynamic-item {
    margin-top: 15px;
  }
}

.header-actions {
  display: flex;
  float: left;
  justify-content: flex-end;
}

.create-resume-button {
  margin-right: 10px;
}

.pagination-wrapper {
  padding-top: 8px;
  display: flex;
  justify-content: flex-end;
}
</style>